using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using Coffee.Utils;

namespace Coffee.SurveyControls.SurveyQuestions
{

    /// <summary>
    /// Summary description for SurveyDropDownList
    /// </summary>


    public class SQDropDownList : SurveyQuestionRow
    {
        public SQDropDownList(SurveyControl parent, XmlNode configuration)
            : base(parent, configuration)
        {
        }

        public override bool Validate()
        {
            return true;
        }

        protected override void Initialize()
        {

        }

        protected override Control CreateCurrentDataControl()
        {
            DropDownList dcurr = new DropDownList();
            dcurr.ID = ctlId;
            dcurr.CssClass = "big-textBoxes";
            return dcurr;
        }

        protected override Control CreatePreviousDataControl()
        {
            Label tprev = new Label();
            tprev.CssClass = "question";
            return tprev;
        }


        public override void LoadDynamicData()
        {
            DropDownList dcurr = (DropDownList)currentAnswerControl;

            string defaultText = string.Empty;
            string defaultValue = string.Empty;
            bool hasDefault = false;
            XmlNode node;

            node = rootNode.SelectSingleNode("default[@item='text']");
            if (node != null)
            {
                hasDefault = true;
                if (node.SelectSingleNode("text()") != null)
                    defaultText = (string)Coffee.Parser.ParseValue(node);
            }

            node = rootNode.SelectSingleNode("default[@item='value']");
            if (node != null)
            {
                hasDefault = true;
                if (node.SelectSingleNode("text()") != null)
                    defaultValue = (string)Coffee.Parser.ParseValue(node);
            }

            dcurr.Items.Clear();
            Coffee.Binding.ConfigureBinding(dcurr, rootNode);
            dcurr.DataBind();

            dcurr.Style.Remove("display");

            if (dcurr.Items.Count == 0)
            {
                dcurr.Style.Add("display", "none");
            }

            if (hasDefault)
            {
                dcurr.Items.Insert(0, new ListItem(defaultText, defaultValue));
            }

        }

        public override void SetupCallBackHandlers()
        {
            ISQEvent evt = config.Event;

            if (evt != null)
            {
                EventHandler handler = null;

                SurveyQuestionRow ctl = (SurveyQuestionRow)SurveyManager.FindControl(evt.Target);

                SurveyManager.Instance.CallBackEvent += delegate(string arg)
                {
                    // get target configuration
                    string[] args = arg.Split(new char[] { '|' });
                    //string srccontrol = args[0];

                    // create a temporary config node 
                    //XmlNode config = configuration.SelectSingleNode("ancestor::tab//*[@id='" + target + "']").CloneNode(true);
                    XmlNode cfg = ctl.Configuration.CloneNode(true);
                    XmlNode data = cfg.SelectSingleNode("data");
                    XmlNode src = data.SelectSingleNode("src[@type='storedproc']");

                    // override the selected parameter with the passed value
                    XmlNode value = src.SelectSingleNode("params/param[name/text()='" + args[1] + "']/value");
                    value.Attributes["src"].Value = "text";
                    value.SelectSingleNode("text()").Value = args[2];

                    // a fake databound control so we can let Coffee handle the binding details
                    JsonDropdownMapper dmap = new JsonDropdownMapper();
                    Coffee.Binding.ConfigureBinding(dmap, cfg);
                    dmap.DataBind();
                    return dmap.ToString();
                };
            }

        }

        public override void SetupClientEventHandlers(Page page)
        {
            ISQEvent evt = config.Event;

            if (evt != null)
            {
                SurveyQuestionRow ctl = (SurveyQuestionRow)SurveyManager.FindControl(evt.Target);

                ctl.HasClientCallback = true;

                ClientScriptManager csm = page.ClientScript;

                string callbackRef = csm.GetCallbackEventReference(
                    page,
                    "'" + config.Id + "|" + evt.Parameters + "|' + document.getElementById('" + this.CurrentControl.ClientID + "').value",
                    ctlId + "EventHandler",
                    "null",
                    "null",
                    true);

                string script = evt.Script.Replace("@source", this.CurrentControl.ClientID).Replace("@target", ctl.CurrentControl.ClientID);

                csm.RegisterStartupScript(page.GetType(), config.Id + "EventHandler", script, true);

                ((DropDownList)currentAnswerControl).Attributes["onchange"] = String.Format("javascript:{0}", callbackRef);

            }

        }


        public override void LoadData()
        {
            //Reload();

            DropDownList dcurr = (DropDownList)currentAnswerControl;
            Label tprev = (Label)previousAnswerControl;

            SQBindingContext binder = new SQBindingContext(rootNode);


            if (Parent.Mapper != null)
            {
                //object[] attributes = Parent.Mapper.Current.GetPropertyAttributes(ctlId);
                bool bDirect = true;
                bool bLookup = false;

                object previousValue = Parent.Mapper.Previous.GetProperty(binder.Previous.PropertyName);

                if (previousValue != null)
                {
                    string prevValue = previousValue.ToString();

                    if (bDirect)
                        tprev.Text = prevValue;

                    if (bLookup)
                    {
                        ListItem li = dcurr.Items.FindByValue(prevValue);
                        if (li != null)
                            tprev.Text = li.Text;
                        else
                            tprev.Text = "<span stlye=\"text-color:#ff0000\">unknown value: #" + prevValue + "#</span>";
                    }
                }
                object currentValue = Parent.Mapper.Current.GetProperty(binder.Current.PropertyName);

                if (currentValue != null)
                {
                    if (binder.Current.Target == "SelectedIndex")
                        dcurr.SelectedIndex = (int)currentValue;
                    else
                        dcurr.SelectedValue = currentValue.ToString();
                }
            }

            dcurr.Enabled = !locked;
        }




        public override void SaveData()
        {
            DropDownList dcurr = (DropDownList)currentAnswerControl;

            SQBindingContext binder = new SQBindingContext(rootNode);

            if (Parent.Mapper != null)
            {
                string selectedvalue;

                if (hasClientCallback)
                {
                    // get the selected value directly because ViewState
                    // is useless for client-modified controls
                    selectedvalue = Parent.Parent.Page.Request.Form[dcurr.UniqueID];
                }
                else
                {
                    // really just the same value as the above, but type-safe
                    // and .NET friendly
                    selectedvalue = dcurr.SelectedValue;
                }

                // should be able to set value to null if selected index or value is an arbitray value
                if (binder.Current.Target == "SelectedIndex")
                {
                    if (hasClientCallback)
                    {
                        Parent.Mapper.Current.SetProperty(binder.Current.PropertyName, dcurr.SelectedIndex);
                    }
                    else
                    {
                        // We don't like what you're doing. Stop it.
                        throw new Exception("SelectedIndex is not valid with a callback in effect. Please consider using the value");
                    }
                }
                else
                {
                    binder.WriteProperties(Parent.Mapper, selectedvalue);
                }
            }
        }


    }
}